<template>
  <div class="container">
      <el-form :model="formData" label-width="80px" class="query-form">
          <el-row :gutter="20">
              <el-col :span="6">
                  <el-form-item label="关联项目">
                      <el-input v-model="formData.AssociatedProjects" />
                  </el-form-item>
              </el-col>
              <el-col :span="6">
                  <el-form-item label="单据主题">
                      <el-input v-model="formData.DocumentSubject" />
                  </el-form-item>
              </el-col>
              <el-col :span="6">
                  <el-form-item label="单据编号">
                      <el-input v-model="formData.DocumentNumber" />
                  </el-form-item>
              </el-col>
          </el-row>
          <el-row :gutter="20">
              <el-col :span="6">
                  <el-form-item label="关联生产订单" label-width="96px">
                      <el-input v-model="formData.AssociateProductionOrder" />
                  </el-form-item>
              </el-col>
              <el-col :span="6">
                  <el-form-item label="加工商">
                      <el-input v-model="formData.Processors" />
                  </el-form-item>
              </el-col>
              <el-col :span="6">
                  <el-form-item label="添加人员">
                      <el-autocomplete
                          v-model="formData.PreparationDocumentsPerson"
                          :fetch-suggestions="fetchAddedBySuggestions"
                          placeholder="请选择或输入"
                          suffix-icon="el-icon-search"
                      />
                  </el-form-item>
              </el-col>
          </el-row>
          <el-row :gutter="20">
              <el-col :span="14">
                  <el-form-item label="添加日期">
                      <el-date-picker
                          v-model="formData.FriPreparationDocumentsDate"
                          type="date"
                      />
                      至
                      <el-date-picker
                          v-model="formData.EndPreparationDocumentsDate"
                          type="date"
                      />
                  </el-form-item>
              </el-col>

              <el-col :span="6">
                  <el-form-item label=" ">
                      <el-button type="primary" @click="getdispatch">查询</el-button>
                  </el-form-item>
              </el-col>
          </el-row>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="20">
          <el-button type="primary" @click="ExcelProduction" :loading="exportLoading">导出Excel</el-button>
          <el-button type="success" @click="handleImport" :loading="importLoading">导入Excel</el-button>
          <el-button type="danger" @click="batchDelete">批量删除</el-button>
        </el-col>
      </el-row>
      <el-table  :data="tableData" style="width: 100%; margin-top: 20px;height: 400px;" @selection-change="handleSelectionChange" ref="multipleTable">
          <el-table-column type="selection" width="55">
              <template #header>
                  <el-checkbox v-model="isAllSelected" @change="handleSelectAll"></el-checkbox>
              </template>
          </el-table-column>
          <el-table-column prop="outsourcingId" label="序号" />
          <el-table-column prop="documentSubject" label="单据主题" />
          <el-table-column prop="documentNumber" label="单据编号"  width="100px" />
          <el-table-column prop="associateProductionOrder" label="关联生产订单" width="110px" />
          <el-table-column prop="processors" label="委外加工商" />
          <el-table-column prop="client" label="客户" width="100px" />
          <el-table-column prop="ourRepresentatives" label="我方代表人" width="100px" />
          <el-table-column prop="paymentPlan" label="付款计划" width="100px" />
          <el-table-column prop="ticketCollectionPlan" label="收票计划" width="100px" />
          <el-table-column prop="automaticallyReceivedInspection" label="是否自动收货送检" width="100px" >
            <template #default="scope">
              {{ scope.row.automaticallyReceivedInspection ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="whetherMaterials" label="是否带料" width="100px" >
            <template #default="scope">
              {{ scope.row.whetherMaterials ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column prop="dateOutsourcing" label="委外日期" width="130px" >
              <template #default="scope">
                  {{ scope.row.dateOutsourcing ? (new Date(scope.row.dateOutsourcing).getFullYear() + '年' + String(new Date(scope.row.dateOutsourcing).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(scope.row.dateOutsourcing).getDate()).padStart(2, '0') + '日') : '' }}
              </template>
          </el-table-column>
          <el-table-column prop="preparationDocumentsDate" label="制单日期" width="130px" >
              <template #default="scope">
                  {{ scope.row.preparationDocumentsDate ? (new Date(scope.row.preparationDocumentsDate).getFullYear() + '年' + String(new Date(scope.row.preparationDocumentsDate).getMonth() + 1).padStart(2, '0') + '月' + String(new Date(scope.row.preparationDocumentsDate).getDate()).padStart(2, '0') + '日') : '' }}
              </template>
          </el-table-column>
          <el-table-column prop="preparationDocumentsPerson" label="制单人员" />
          <el-table-column prop="associatedProjects" label="关联项目" width="120px" />
          <el-table-column prop="remark" label="备注" width="120px" />
          <el-table-column prop="outsourcingId" label="操作" width="150px" fixed="right" >
              <template #default="scope">
                  <el-button type="danger" link @click="() => deleteItem(String(scope.row.outsourcingId))">删除</el-button>
                  <el-button type="warning" link @click="() => editItem(String(scope.row.outsourcingId))">编辑</el-button>
              </template>
          </el-table-column>
      </el-table>
  </div>
  <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="page.PageIndex"
          v-model:page-size="page.PageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
  </div>
  <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;">
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { write, read } from '@/axios/axiosHelper';

const router = useRouter();

const formData = ref({
  AssociatedProjects: '',
  DocumentSubject: "",
  DocumentNumber: "",
  AssociateProductionOrder: "",
  Processors: "",
  PreparationDocumentsPerson: "",
  FriPreparationDocumentsDate: "",
  EndPreparationDocumentsDate: "",
});

const tableData = ref([]);
const multipleSelection = ref([]);
const isAllSelected = ref(false);
const exportLoading = ref(false);
const importLoading = ref(false);

onMounted(() => {
  getdispatch();
});

const page = ref({
  PageIndex: 1,
  PageSize: 50
})

const total = ref({
  totalCount: 0,
  totalPage: 0,
})

// 查询显示委外数据
const getdispatch = () => {
  read.get('w-read/api/Report/GetOutsourcing', {
      params: {
          PageIndex: page.value.PageIndex,
          PageSize: page.value.PageSize,
          AssociatedProjects: formData.value.AssociatedProjects,
          DocumentSubject: formData.value.DocumentSubject,
          DocumentNumber: formData.value.DocumentNumber,
          AssociateProductionOrder: formData.value.AssociateProductionOrder,
          Processors: formData.value.Processors,
          PreparationDocumentsPerson: formData.value.PreparationDocumentsPerson,
          FriPreparationDocumentsDate: formData.value.FriPreparationDocumentsDate,
          EndPreparationDocumentsDate: formData.value.EndPreparationDocumentsDate,
      }
  }).then((res) => {
      tableData.value = res.data.data.list;
      total.value.totalCount = res.data.data.totalCount;
      total.value.totalPage = res.data.data.totalPage;
      isAllSelected.value = false;
  }).catch(error => {
      ElMessage.error('查询失败，请检查网络或参数');
      console.error(error);
  });
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  isAllSelected.value = multipleSelection.value.length === tableData.value.length;
}

const handleSelectAll = (val) => {
  const table = ref(null).value;
  if (val) {
      tableData.value.forEach(row => {
          table.toggleRowSelection(row, true);
      });
  } else {
      tableData.value.forEach(row => {
          table.toggleRowSelection(row, false);
      });
  }
}

const handleSizeChange = (val) => {
  page.value.PageSize = val;
  getdispatch();
}

const handleCurrentChange = (val) => {
  page.value.PageIndex = val;
  getdispatch();
}

// 自动完成建议函数（需根据实际接口实现）
const fetchAddedBySuggestions = (query, cb) => {
  // 这里应调用实际的建议数据接口
  const suggestions = [];
  cb(suggestions);
}

// 导出Excel表
const ExcelProduction = async () => {
  exportLoading.value = true;
  try {
    const response = await read.get('w-read/api/Report/OutExportToExcel', {
      responseType: 'blob'
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'production_data.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败，请重试');
    console.error(error);
  } finally {
    exportLoading.value = false;
  }
}

//导入Excel表
const fileInput = ref(null);

const handleImport = () => {
  fileInput.value.click();
};

const handleFileChange = async (event) => {
  const files = event.target.files;
  if (files.length > 0) {
    const file = files[0];
    const formData = new FormData();
    formData.append('file', file); // 假设后端接口接收的文件参数名为 'file'

    try {
      const response = await write.post('w-write/api/Outsourcing/ImportExcel', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      console.log('导入成功:', response.data);
    } catch (error) {
      console.error('导入失败:', error);
    }
  }
  // 清空输入框，以便下次选择相同文件时也能触发 change 事件
  fileInput.value.value = '';
  getdispatch();
};

// 单个删除方法
const deleteItem = (id) => {
  ElMessageBox.confirm('确定要删除该条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    write.post('w-write/api/Outsourcing/DelOutsourcing', { ids: id })
     .then((res) => {
        if (res.data.code === 100) {
          ElMessage.success('删除成功');
          getdispatch(); // 重新获取数据
        } else {
          ElMessage.error(res.data.message);
        }
      })
     .catch((error) => {
        ElMessage.error('删除失败，请重试');
      });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 编辑方法
const editItem = (outsourcingId) => {
  router.push({
    name: 'GetBYIdOutsourcing', // 确保路由配置正确
    query: {
      outsourcingId: outsourcingId
    }
  });
  console.log('编辑ID:', outsourcingId);
}

// 批量删除方法
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  ElMessageBox.confirm('确定要批量删除选中的数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.outsourcingId).join(',');
    write.post('w-write/api/Outsourcing/DelOutsourcing', { ids })
     .then((res) => {
        if (res.data.code === 100) {
          ElMessage.success('批量删除成功');
          getdispatch(); // 重新获取数据
        } else {
          ElMessage.error(res.data.message);
        }
      })
     .catch((error) => {
        ElMessage.error('批量删除失败，请重试');
      });
  }).catch(() => {
    ElMessage.info('已取消批量删除');
  });
}
</script>

<style scoped>
.query-form {
  margin-bottom: 20px;
}
</style>